import path from "path";
import { readFileSync } from "fs";
import webpack from "webpack";
import HtmlWebpackPlugin from "html-webpack-plugin";
import { VueLoaderPlugin } from "vue-loader";
import { CleanWebpackPlugin } from "clean-webpack-plugin";
import CopyPlugin from "copy-webpack-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
// import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
// import TerserPlugin from "terser-webpack-plugin";
// import CompressionPlugin from "compression-webpack-plugin";

// 项目根目录
const rootDir = process.cwd();

// console.log("----process.env.NODE_ENV----", process.env.NODE_ENV);

// const devMode = process.env.NODE_ENV !== "production";

// console.log("---- devMode ---", devMode);

// 获取存在本地的配置信息
const getConfigInfo = () => {
  const envConfigPath = path.resolve(rootDir, "version", "app.json");
  try {
    const configStr = readFileSync(envConfigPath, "utf-8");
    return JSON.parse(configStr);
  } catch (err) {
    console.log(err);
  }
};

const envConfig = getConfigInfo();
// 如果是serve，则设置为真实的serve环境
if (process.argv.indexOf("serve") !== -1) {
  envConfig.env = process.env.NODE_ENV;
}

const config = {
  entry: "./src/main.ts",
  output: {
    path: path.resolve(rootDir, "dist"),
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
    alias: {
      "@": path.resolve(rootDir, "src"),
    },
  },
  module: {
    rules: [
      {
        test: /\.(mp3)(\?.*)?$/,
        loader: "url-loader",
      },
      {
        test: /\.(eot|svg|ttf|woff2?|)$/,
        type: "asset/resource",
        generator: {
          filename: "fonts/[name]-[hash][ext]",
        },
      },
      {
        test: /\.(png|svg|jpe?g|gif)$/,
        type: "asset",
        generator: {
          filename: "img/[name]-[hash][ext]",
        },
      },
      {
        test: /\.(sa|sc|c)ss$/,
        // "style-loader"
        // MiniCssExtractPlugin.loader,
        // "css-loader",
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: [
                  [
                    "postcss-pxtorem",
                    {
                      rootValue: ({ file }) => {
                        return file.indexOf("vant") !== -1 ? 37.5 : 75;
                      },
                      propList: ["*"],
                    },
                  ],
                ],
              },
            },
          },
          "sass-loader",
          {
            loader: "sass-resources-loader",
            options: {
              resources: [path.resolve(rootDir, "src/assets/css/index.scss")],
            },
          },
        ],
      },
      {
        test: /\.(t|j)s$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            cacheDirectory: true,
          },
        },
      },
      {
        test: /\.vue$/,
        use: "vue-loader",
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "年度报告",
      template: "./public/index.html",
    }),
    new VueLoaderPlugin(),
    new webpack.ProgressPlugin({}),
    new webpack.DefinePlugin({
      "process.env": {
        CONFIG: JSON.stringify(envConfig),
      },
    }),
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(rootDir, "public/images"),
          to: path.resolve(rootDir, "dist/images"),
        },
      ],
    }),
    new CleanWebpackPlugin(),
    // new BundleAnalyzerPlugin({ analyzerPort: 8081 }),
    new MiniCssExtractPlugin(),
    // new CompressionPlugin({
    //   algorithm: "gzip",
    //   threshold: 10240,
    //   minRatio: 0.8,
    // }),
  ],
  // optimization: {
  //   minimizer: [
  //     new TerserPlugin({
  //       terserOptions: {
  //         compress: {
  //           drop_console: true,
  //         },
  //       },
  //     }),
  //   ],
  // },
  cache: {
    type: "filesystem",
  },
};

export default config;
